//
//  RMMChooseFuWuViewController.m
//  Romomo
//
//  Created by puman on 2017/2/7.
//  Copyright © 2017年 mazegong. All rights reserved.
//

#import "RMMChooseFuWuViewController.h"
#import "RMMChooseFuWuHeadView.h"
#import "RMMShopingTableViewCell.h"
#import "RMMChooseFuWuBottomView.h"
#import "RMMGoodsConfirmViewController.h"
#import "RMMGoodsDetialsViewController.h"
#import "RMMMyHuLiTableViewCell.h"
#import "RMMTaoCanDetailsViewController.h"
#import "RMMChosseDateViewController.h"
#import "RMMGoodsConfirmViewController.h"

@interface RMMChooseFuWuViewController ()<UITableViewDelegate, UITableViewDataSource>

@end

@implementation RMMChooseFuWuViewController
{
    NSInteger _buttonTag;
    UITableView *_tableView;
    RMMChooseFuWuHeadView *_headView;
    RMMChooseFuWuBottomView *_bottomView;
    NSMutableArray *_array;
    NSMutableDictionary *_dataDic;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"选择服务项目";
    self.view.backgroundColor = kCColor;
    [self addViews];
    __weak RMMChooseFuWuViewController *mySelf = self;
    [mySelf addFresh];
    // Do any additional setup after loading the view.
}
- (void)addViews{
    _buttonTag = 10;
    _dataDic = [NSMutableDictionary dictionary];
    [self addFuWuType];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, _headView.bottom, kScreenWideth, kScreenHeight - 49 - _headView.bottom - 64) style:(UITableViewStylePlain)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = NO;
    [_tableView registerClass:[RMMMyHuLiTableViewCell class] forCellReuseIdentifier:@"MyCell"];
    [_tableView registerClass:[RMMShopingTableViewCell class] forCellReuseIdentifier:@"Cell"];
    [self.view addSubview:_tableView];
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 0)];
    _bottomView = [[RMMChooseFuWuBottomView alloc] initWithFrame:CGRectMake(0, _tableView.bottom, kScreenWideth, 49)];
    [self.view addSubview:_bottomView];
    BUTTON_S(_bottomView.goBuyBut, goBuyButClick);
}
- (void)addFresh{
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSDictionary *keyDic = _array[_buttonTag - 10];
        [self getRequestDataWith:keyDic[@"CateId"] forPage:@""];
    }];
}
- (void)addFuWuType{
    _array = [NSMutableArray array];
    for (NSDictionary *dic in [RMMFileManager shareHandle].fuWuTypeArray) {
        [_array addObject:dic];
        NSMutableArray *value = [NSMutableArray array];
        [_dataDic setObject:value forKey:dic[@"CateName"]];
    }
    NSDictionary *dic = @{@"CateId":@"",@"CateName":@"我的套餐"};
    NSMutableArray *value = [NSMutableArray array];
    [_dataDic setObject:value forKey:@"我的套餐"];
    
    [_array addObject:dic];
    _headView= [[RMMChooseFuWuHeadView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 54) array:_array];
    [self.view addSubview:_headView];
    for (int i = 0; i < _array.count; i++) {
        UIButton *button = [self.view viewWithTag:10 + i];
        BUTTON_S(button, buttonClick:);
    }
    [self getRequestDataWith:_array[0][@"CateId"] forPage:@""];
}
- (void)buttonClick:(UIButton *)button{
    _buttonTag = button.tag;
    for (int i = 0; i < _array.count; i++) {
        UIButton *buttons = [self.view viewWithTag:10 + i];
        if (buttons.tag == _buttonTag) {
            [buttons setTitleColor:COLORFROMCODE(0x2C2C2C, 1) forState:(UIControlStateNormal)];
            buttons.backgroundColor = COLORFROMCODE(0xEEEEEE, 1);
            buttons.userInteractionEnabled = NO;
        } else {
            [buttons setTitleColor:COLORFROMCODE(0xBFBFBF, 1) forState:(UIControlStateNormal)];
            buttons.backgroundColor = kWhiteColor;
            buttons.userInteractionEnabled = YES;
        }
    }
    NSDictionary *keyDic = _array[_buttonTag - 10];
    NSString *key = keyDic[@"CateName"];
    NSMutableArray *value = _dataDic[key];
    if (!value.count) {
        [self getRequestDataWith:keyDic[@"CateId"] forPage:@""];
    }
    [_tableView reloadData];
}
-  (void)getRequestDataWith:(NSString *)type forPage:(NSString *)page{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    NSString *url = nil;
    if (_buttonTag == _array.count - 1 + 10) {
        parDic[@"org_no"] = Org_no;
        parDic[@"cust_id"] = [RMMFileManager shareHandle].userDic[@"CUST_ID"];
        url = GetCustBomUrl;
    } else {
        parDic[@"org_no"] = Org_no;
        parDic[@"prod_type"] = _isHome;
        parDic[@"region_id"] = [RMMFileManager shareHandle].region_id;
        parDic[@"pageindex"] = page;
        parDic[@"type"] = type;
        url = HomeOneClassDataUrl;
    }
    [OSRequestManager requestWithUrlString:url parDic:parDic network:^(BOOL isNetwork) {
        if (!isNetwork) {
            [_tableView.mj_header endRefreshing];
        }
    } method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            NSDictionary *keyDic = _array[_buttonTag - 10];
            NSString *key = keyDic[@"CateName"];
            NSMutableArray *value = _dataDic[key];
            [value removeAllObjects];
            if ([url isEqualToString:GetCustBomUrl]) {
                NSArray *array = dataDic[@"data"];
                for (NSDictionary *dic in array) {
                    NSArray *arr = dic[@"CARD_DETAILS"];
                    for (NSDictionary *newDic in arr) {
                        RMMHuLiModel *model = [[RMMHuLiModel alloc] init];
                        [model setValuesForKeysWithDictionary:[RMMFileManager setValueForDic:newDic]];
                        model.isSelect = @"0";
                        model.COUNT = @"1";
                        model.BOM_ID = dic[@"BOM_ID"];
                        if ([model.IS_HOME isEqualToString:[RMMFileManager shareHandle].fuWuType]) {
                            [value addObject:model];
                        }
                    }
                }
                [self sortArrayWith:value];
            } else {
                NSArray *array = dataDic[@"data"];
                for (NSDictionary *dic in array) {
                    RMMShopingModel *model = [[RMMShopingModel alloc] init];
                    [model setValuesForKeysWithDictionary:[RMMFileManager setValueForDic:dic]];
                    model.MY_CARD_ID = @"0";
                    [value addObject:model];
                }
            }
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
        [_tableView reloadData];
        [_tableView.mj_header endRefreshing];
    } error:^(NSError *errors) {
        [_tableView.mj_header endRefreshing];
    } view:self.view];
}
- (void)sortArrayWith:(NSMutableArray *)array{
    NSMutableArray *arrayA = [NSMutableArray array];
    NSMutableArray *arrayB = [NSMutableArray array];
    
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSString *string = [inputFormatter stringFromDate:date];
    
    for (RMMHuLiModel *model in array) {
        NSString *time = [RMMFileManager retrunObjWith:model.END_DATE];
        if ([model.AVA_QTY integerValue] == 0) {
            [arrayA addObject:model];
        } else {
            if ([time compare:string] == NSOrderedAscending) {
                [arrayA addObject:model];
            } else {
                [arrayB addObject:model];
            }
        }
    }
    if (arrayB.count > 1) {
        for (int i = 0; i < arrayB.count - 1; i++) {
            int maxIndex = i;
            for (int j = i+ 1; j < arrayB.count; j++) {
                RMMHuLiModel *modelA = arrayB[j];
                RMMHuLiModel *modelB = arrayB[maxIndex];
                if ([modelA.MY_CARD_ID floatValue] > [modelB.MY_CARD_ID floatValue]) {
                    maxIndex = j;
                }
            }
            if (i != maxIndex) {
                [arrayB exchangeObjectAtIndex:i withObjectAtIndex:maxIndex];
            }
        }
    }
    for (int i = 0; i < arrayB.count - 1; i++) {
        for (int j = 0; j < arrayB.count - 1 - i; j++) {
            RMMHuLiModel *modelA = array[j];
            RMMHuLiModel *modelB = array[j + 1];
            if ([modelA.MY_CARD_ID floatValue] < [modelB.MY_CARD_ID floatValue]) {
                [arrayB exchangeObjectAtIndex:j withObjectAtIndex:j+1];
            }
        }
    }
    [array removeAllObjects];
    [array addObjectsFromArray:arrayB];
    [array addObjectsFromArray:arrayA];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSDictionary *keyDic = _array[_buttonTag - 10];
    NSString *key = keyDic[@"CateName"];
    if (_dataDic == nil) {
        return 0;
    }
    NSArray *array = _dataDic[key];
    return array.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_buttonTag == _array.count - 1 + 10) {
        return 160;
    } else {
        return 90;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_buttonTag == _array.count - 1 + 10) {
        RMMMyHuLiTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSMutableArray *value = _dataDic[@"我的套餐"];
        cell.selectBut.tag = indexPath.row + 100 + _buttonTag * 10000;
        cell.subBut.tag = indexPath.row + 200 + _buttonTag * 10000;
        cell.addBut.tag = indexPath.row + 300 + _buttonTag * 10000;
        BUTTON_S(cell.selectBut, cellSelectButClick:);
        BUTTON_S(cell.subBut, subButClick:);
        BUTTON_S(cell.addBut, addButClick:);
        cell.model = value[indexPath.row];
        return cell;
    } else {
        RMMShopingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSDictionary *keyDic = _array[_buttonTag - 10];
        NSString *key = keyDic[@"CateName"];
        NSArray *array = _dataDic[key];
        RMMShopingModel *model = array[indexPath.row];
        cell.model = model;
        cell.cellSelectBut.tag = indexPath.row + 100 + _buttonTag * 10000;
        cell.subBut.tag = indexPath.row + 200 + _buttonTag * 10000;
        cell.addBut.tag = indexPath.row + 300 + _buttonTag * 10000;
        BUTTON_S(cell.cellSelectBut, cellSelectButClick:);
        BUTTON_S(cell.subBut, subButClick:);
        BUTTON_S(cell.addBut, addButClick:);
        
        if ([model.isSelect isEqualToString:@"1"]) {
            [cell.cellSelectBut setImage:[UIImage imageNamed:@"选中@3x"] forState:(UIControlStateNormal)];
        } else {
            [cell.cellSelectBut setImage:[UIImage imageNamed:@"可选@3x"] forState:(UIControlStateNormal)];
        }
        cell.countLabel.text = [NSString stringWithFormat:@"%@",model.COUNT];
        if ([model.COUNT isEqualToNumber:@1]) {
            [cell.subBut setImage:[UIImage imageNamed:@"un-subtract@3x"] forState:(UIControlStateNormal)];
            cell.subBut.userInteractionEnabled = NO;
        } else {
            [cell.subBut setImage:[UIImage imageNamed:@"subtract@3x"] forState:(UIControlStateNormal)];
            cell.subBut.userInteractionEnabled = YES;
        }
        return cell;
        
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *keyDic = _array[_buttonTag - 10];
    NSString *key = keyDic[@"CateName"];
    NSArray *array = _dataDic[key];
    RMMShopingModel *model = array[indexPath.row];
    if (![key isEqualToString:@"我的套餐"]) {
        RMMGoodsDetialsViewController *VC = [[RMMGoodsDetialsViewController alloc] init];
        VC.mySkill = @"1";
        VC.service_id = [RMMFileManager retrunObjWith:model.SERVICE_ID];
        [self.navigationController pushViewController:VC animated:YES];
    } else {
        return;
//        RMMTaoCanDetailsViewController *VC = [[RMMTaoCanDetailsViewController alloc] init];
//        VC.mySkill = @"1";
//        VC.bom_id = [RMMFileManager retrunObjWith:model.BOM_ID];
//        [self.navigationController pushViewController:VC animated:YES];
    }
}
- (void)cellSelectButClick:(UIButton *)button{
    NSDictionary *keyDic = _array[_buttonTag - 10];
    NSString *key = keyDic[@"CateName"];
    NSMutableArray *array = _dataDic[key];
    if ([key isEqualToString:@"我的套餐"]) {
        RMMHuLiModel *model = array[button.tag - 100 - 10000 * _buttonTag];
        if ([model.isSelect isEqualToString:@"1"]) {
            model.isSelect = @"0";
            [button setImage:[UIImage imageNamed:@"可选@3x"] forState:(UIControlStateNormal)];
        } else {
            model.isSelect = @"1";
            [button setImage:[UIImage imageNamed:@"选中@3x"] forState:(UIControlStateNormal)];
        }
    } else {
        RMMShopingModel *model = array[button.tag - 100 - 10000 * _buttonTag];
        if ([model.isSelect isEqualToString:@"1"]) {
            model.isSelect = @"0";
            [button setImage:[UIImage imageNamed:@"可选@3x"] forState:(UIControlStateNormal)];
        } else {
            model.isSelect = @"1";
            [button setImage:[UIImage imageNamed:@"选中@3x"] forState:(UIControlStateNormal)];
        }
    }
    CGFloat totalPrice = [self getToatalPriceWithArray:_dataDic];
    _bottomView.totalPriceLabel.text = [NSString stringWithFormat:@"总计: ¥%.2f",totalPrice];
    [_tableView reloadData];
    [self cancelButSelcet];
    for (NSString *key in _dataDic) {
        NSMutableArray *value = _dataDic[key];
        if ([key isEqualToString:@"我的套餐"]) {
            for (RMMHuLiModel *model in value) {
                if ([model.isSelect isEqualToString:@"1"]) {
                    [self goBuyButSelcet];
                    return;
                }
            }
        } else {
            for (RMMShopingModel *model in value) {
                if ([model.isSelect isEqualToString:@"1"]) {
                    [self goBuyButSelcet];
                    return;
                }
            }
        }
    }
}
- (void)subButClick:(UIButton *)button{
    NSDictionary *keyDic = _array[_buttonTag - 10];
    NSString *key = keyDic[@"CateName"];
    NSMutableArray *array = _dataDic[key];
    if ([key isEqualToString:@"我的套餐"]) {
        RMMHuLiModel *model = array[button.tag - 200 - 10000 * _buttonTag];
        NSInteger count = [model.COUNT integerValue];
        if (count == 1) {
            [button setImage:[UIImage imageNamed:@"un-subtract@3x"] forState:(UIControlStateNormal)];
            button.userInteractionEnabled = NO;
        } else {
            count -= 1;
            model.COUNT = [NSString stringWithFormat:@"%ld",count];
        }
    } else {
        RMMShopingModel *model = array[button.tag - 200 - 10000 * _buttonTag];
        NSInteger cout = [model.COUNT integerValue];
        if (cout == 1) {
            [button setImage:[UIImage imageNamed:@"un-subtract@3x"] forState:(UIControlStateNormal)];
            button.userInteractionEnabled = NO;
        } else {
            cout -= 1;
            model.COUNT = [NSNumber numberWithInteger:cout];
        }
    }
    CGFloat totalPrice = [self getToatalPriceWithArray:_dataDic];
    _bottomView.totalPriceLabel.text = [NSString stringWithFormat:@"总计: ¥%.2f",totalPrice];
    [_tableView reloadData];
}
- (void)addButClick:(UIButton *)button{
    NSDictionary *keyDic = _array[_buttonTag - 10];
    NSString *key = keyDic[@"CateName"];
    NSMutableArray *array = _dataDic[key];
    if ([key isEqualToString:@"我的套餐"]) {
        RMMHuLiModel *model = array[button.tag - 300 - 10000 * _buttonTag];
        NSInteger count = [model.COUNT integerValue];
        if (count == [model.AVA_QTY integerValue]) {
            [RMMFileManager MBProgressWith:@"可用次数不足!" onView:self.view];
            return;
        } else {
            count += 1;
            model.COUNT = [NSString stringWithFormat:@"%ld",count];
            if (count >= 2) {
                UIButton *but = [self.view viewWithTag:button.tag - 100];
                [but setImage:[UIImage imageNamed:@"subtract@3x"] forState:(UIControlStateNormal)];
                but.userInteractionEnabled = YES;
            }
        }
    } else {
        RMMShopingModel *model = array[button.tag - 300 - 10000 * _buttonTag];
        NSInteger cout = [model.COUNT integerValue];
        if (cout == 99) {
            [RMMFileManager MBProgressWith:@"单一服务数量不能超过99!" onView:self.view];
        } else {
            cout += 1;
            model.COUNT = [NSNumber numberWithInteger:cout];
            if (cout >= 2) {
                UIButton *but = [self.view viewWithTag:button.tag - 100];
                [but setImage:[UIImage imageNamed:@"subtract@3x"] forState:(UIControlStateNormal)];
                but.userInteractionEnabled = YES;
            }
        }
    }
    [_tableView reloadData];
    CGFloat totalPrice = [self getToatalPriceWithArray:_dataDic];
    _bottomView.totalPriceLabel.text = [NSString stringWithFormat:@"总计: ¥%.2f",totalPrice];
}
- (CGFloat)getToatalPriceWithArray:(NSMutableDictionary *)dataDic{
    CGFloat totalPrcie = 0.00;
    for (NSString *key in dataDic) {
        if (![key isEqualToString:@"我的套餐"]) {
            NSMutableArray *value = dataDic[key];
            for (RMMShopingModel *model in value) {
                if ([model.isSelect isEqualToString:@"1"]) {
                    CGFloat prcie = [model.PRICE floatValue];
                    NSInteger count = [model.COUNT integerValue];
                    totalPrcie += prcie * count;
                }
            }
        }
    }
    //_totalPrice = totalPrcie;
    return totalPrcie;
}
- (void)goBuyButClick{
    RMMGoodsConfirmViewController *VC = [[RMMGoodsConfirmViewController alloc] init];
    VC.goodsArray = [NSMutableArray array];
    CGFloat totalTime = 0.00;
    [[RMMFileManager shareHandle].skillBookingArray removeAllObjects];
    for (NSString *key in _dataDic) {
        NSMutableArray *value = _dataDic[key];
        if ([key isEqualToString:@"我的套餐"]) {
            for (RMMHuLiModel *model in value) {
                if ([model.isSelect isEqualToString:@"1"]) {
                    RMMShopingModel *taoModel = [[RMMShopingModel alloc] init];
                    taoModel.IMAGEURL = model.SER_URL;
                    taoModel.SERVICE_ID = [NSString stringWithFormat:@"%@",model.SERVER_ID];
                    taoModel.PRICE = [NSString stringWithFormat:@"%@",model.PRICE];
                    taoModel.COUNT = [NSNumber numberWithInteger: [model.COUNT integerValue]];
                    taoModel.SERVICE_NAME = model.NAME;
                    taoModel.MY_CARD_ID = [NSString stringWithFormat:@"%@",model.MY_CARD_ID];
                    taoModel.TIME_LEN = model.TIME_LEN;
                    totalTime += [model.TIME_LEN floatValue];
                    taoModel.PROD_SERVICE_TYPE = model.PROD_SERVICE_TYPE;
                    [VC.goodsArray addObject:taoModel];
                }
            }
        } else {
            for (RMMShopingModel *model in value) {
                if ([model.isSelect isEqualToString:@"1"]) {
                    totalTime += [model.TIME_LEN floatValue] * [model.COUNT integerValue];
                    [VC.goodsArray addObject:model];
                }
            }
        }
    }
    if (VC.goodsArray.count == 1) {
        RMMShopingModel *model = VC.goodsArray[0];
        if ([model.PROD_SERVICE_TYPE isEqualToString:@"1"] && ([model.COUNT isEqualToNumber:@1])) {
            [RMMFileManager MBProgressWith:@"辅助项目不能单独购买!" onView:self.view];
            return;
        }
    }
    [RMMFileManager shareHandle].totalTimeLength = [NSString stringWithFormat:@"%.0f",totalTime];
    VC.tabBarController.hidesBottomBarWhenPushed = YES;
    VC.isHome = _isHome;
    [self.navigationController pushViewController:VC animated:YES];
}
- (void)goBuyButSelcet{
    [_bottomView.goBuyBut setTitleColor:kWhiteColor forState:(UIControlStateNormal)];
    _bottomView.goBuyBut.backgroundColor = COLORFROMCODE(0x53C7C6, 1);
    _bottomView.goBuyBut.userInteractionEnabled = YES;
}
- (void)cancelButSelcet{
    [_bottomView.goBuyBut setTitleColor:COLORFROMCODE(0xD7D7D7, 1) forState:(UIControlStateNormal)];
    _bottomView.goBuyBut.backgroundColor = COLORFROMCODE(0xEEEEEE, 1);
    _bottomView.goBuyBut.userInteractionEnabled = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
